﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jenzabar.Portal.Framework.Web.UI;
using Jenzabar.Portal.Framework;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Drawing;
using Jenzabar.Common.Globalization;
using Jenzabar.Common.Mail;//Req For PortletViewBase
using Jenzabar.Portal.Framework.EmailLogging;
using ConfigSettings = Jenzabar.Common.Configuration.ConfigSettings;

namespace Portlet.AURoster
{
    public partial class Edit_View : PortletViewBase 
    {
        protected void lnkSearch_Click(object sender, EventArgs e)
        {
            this.ParentPortlet.NextScreen("Search");
        }

        string cid ="";
        protected void Page_Load(object sender, EventArgs e)
        {
            cid = PortalUser.Current.HostID;
            lblCoach.Text = PortalUser.Current.FirstName + " " + PortalUser.Current.LastName;
            lblDate.Text = DateTime.Now.ToShortDateString();
          
                BindGV(gvPlayer, cid);
            

        }

        private void BindGV(GridView gv, string coach)
        {
            using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
            {

                try
                {
                    myConn.Open();
                    cid = PortalUser.Current.HostID;
                    SqlCommand cmd = new SqlCommand("Select Student_ID,  Last_Name, First_Name, No_of_Competed, NAIA_EC#,HS_OR_College,HS_GRAD_DATE ,  [Status]  from [TmsEprd].[dbo].[CUS_AURoster_Team] WHERE [Coach_ID] ='" + coach + "'  Order by Last_Name ", myConn);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);

                    //DataTable dt = new DataTable();
                    
                    DataSet ds = new DataSet();

                    da.Fill(ds, "DataView");
                    Session["myTable"] = ds;
                    gv.DataSource = ds;
                    gv.DataBind();


                }
                catch (Exception ex)
                {


                    this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error Binding Data Items: " + ex.Message);
                }
                finally
                {
                    // Close Connection
                    myConn.Close();
                }
            }
        }

        protected void gvPlayer_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string SID = (string)gvPlayer.DataKeys[e.RowIndex].Value;
            DeleteRecordByID(SID);
            BindGV(gvPlayer, cid);
        }

        private void DeleteRecordByID(string SID)
        {
            using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
            {

                try
                {
                    myConn.Open();

                    SqlCommand cmd = new SqlCommand("Delete from [TmsEprd].[dbo].[CUS_AURoster_Team] WHERE [Student_ID] = '" + SID + "'", myConn);
                    cmd.ExecuteNonQuery();


                }
                catch (Exception ex)
                {


                    this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error retreiving Data Items: " + ex.Message);
                }
                finally
                {
                    // Close Connection
                    myConn.Close();
                }
            }
        }

        protected void gvPlayer_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
               string SID = e.CommandArgument.ToString();
                // Delete the record 
                DeleteRecordByID(SID); 

            }
          

        }

        protected void gvPlayer_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("lnkDelete");
                l.Attributes.Add("onclick", "javascript:return " +
                "confirm('Are you sure you want to delete this record " +
                DataBinder.Eval(e.Row.DataItem, "Student_ID") + "')");
               

                //if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                //{
                    //Label sid = (Label)e.Row.FindControl("lblID");
                    //sid.Text = drv[0].ToString();



                    //DropDownList dd = (DropDownList)e.Row.FindControl("ddStatus");
                    //populateDD(dd);

                    //dd.SelectedValue = drv[2].ToString(); // Position of status column in gridView(starts from "0")

                    //CheckBoxList chkb = (CheckBoxList)e.Row.FindControl("CBActive");
                    //chkb.SelectedValue = drv[8].ToString(); // Array Position of Active column in gridView(starts from "0")

                    //Also add Radiobuttons like below
                    //RadioButtonList rbtnl = (RadioButtonList)e.Row.FindControl("RadioButtonList1");
                    //rbtnl.SelectedValue = drv[5].ToString();
                //}




            }
        }

        private void populateDD(DropDownList dd)
        {
            List<lsStatus> lstStr = new List<lsStatus>();

            lstStr.Add(new lsStatus("New FR", "New FR"));
            lstStr.Add(new lsStatus("New TR", "New TR"));
            lstStr.Add(new lsStatus("Return", "Return"));
            lstStr.Add(new lsStatus("Delete", "Delete"));

            dd.DataSource = lstStr;
            dd.DataValueField = "StatusCode";
            dd.DataTextField = "StatusValue";
            dd.DataBind();
        }

        protected void gvPlayer_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            BindGV(gvPlayer, cid);
        }

       



        private void UpdateRecord(string SID, string fname, string lname, string status ,string compete , string naia, string hs, string gdate)//, string dd, string cb)
        {
            using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
            {

                try
                {
                    myConn.Open();

                    SqlCommand cmd = new SqlCommand("CUS_sp_AURoster_Player_Update", myConn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@first", SqlDbType.VarChar).Value = fname;
                    cmd.Parameters.Add("@last", SqlDbType.VarChar).Value = lname;
                    cmd.Parameters.Add("@status", SqlDbType.VarChar).Value = status;
                    cmd.Parameters.Add("@sid", SqlDbType.VarChar).Value = SID;
                    cmd.Parameters.Add("@compete", SqlDbType.VarChar, 100).Value = Convert.ToInt32(compete);
                    cmd.Parameters.Add("@ec#", SqlDbType.VarChar).Value = naia;
                    cmd.Parameters.Add("@hs", SqlDbType.VarChar).Value = hs;
                    cmd.Parameters.Add("@gdate", SqlDbType.VarChar).Value = gdate;
                    cmd.ExecuteNonQuery();
                   


                }
                catch (Exception ex)
                {


                    this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error Updating Data Items: " + ex.Message);
                }
                finally
                {
                    // Close Connection
                    myConn.Close();
                }
            }
        }

     

       

        protected void gvPlayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            dv.Visible = true;
            //dv to edit Mode
            dv.ChangeMode(DetailsViewMode.Edit);
            populateDV();
            
        }

        
        private void populateDV()
        {
            using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
            {

                try
                {
                    myConn.Open();
                    //GridViewRow selectedRow = gvPlayer.SelectedRow;
                    int selectedIndex = gvPlayer.SelectedIndex;
                    //Read the ID From the row
                     string id = (gvPlayer.DataKeys[selectedIndex].Value).ToString();
          
                   // selectedRowSID = selectedRow.Cells[0].Text;
                    SqlCommand cmd = new SqlCommand("SELECT * FROM [TmsEprd].[dbo].[CUS_AURoster_Team] WHERE Student_ID = '" + id +"'" , myConn);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);

                    DataSet ds = new DataSet();

                    da.Fill(ds, "DataView");
                    
                    //SqlDataReader reader;
                    //reader = cmd.ExecuteReader();
                    dv.DataSource = ds;
                    dv.DataBind();
                }
                catch (Exception ex)
                {
                    this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error retrieving Data. test " + ex.Message);
                    // this.ParentPortlet.NextScreen("Default");

                }
                finally
                {

                    myConn.Close();
                }

            }
        }

        protected void dv_ModeChanging(object sender, DetailsViewModeEventArgs e)
        {
            dv.ChangeMode(e.NewMode);
            populateDV();
            if (e.NewMode == DetailsViewMode.ReadOnly)
            {
                if (e.CancelingEdit || e.Cancel)
                {
                    dv.Visible = false;

                }
            }
          
           
          
        }

        protected void dv_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
           
             int selectedIndex = gvPlayer.SelectedIndex;
                    //Read the ID From the row
             string SID = (gvPlayer.DataKeys[selectedIndex].Value).ToString();
            TextBox fname = (TextBox)dv.FindControl("first");
             TextBox lname = (TextBox)dv.FindControl("Last");
             DropDownList ddstatus = (DropDownList)dv.FindControl("ddStatus");
             TextBox compete = (TextBox)dv.FindControl("txtCompete");
             TextBox naia = (TextBox)dv.FindControl("txtEC");
             TextBox hs = (TextBox)dv.FindControl("txtHS");
             TextBox gdate = (TextBox)dv.FindControl("txtDate");
             UpdateRecord(SID, fname.Text, lname.Text, ddstatus.SelectedValue.ToString(), compete.Text, naia.Text, hs.Text, gdate.Text);
             sendEmail(SID, fname.Text, lname.Text, ddstatus.SelectedValue.ToString(), compete.Text, naia.Text, hs.Text, gdate.Text);
            //Added this time stamp on March 28 2014
            string dt;
            dt = DateTime.Now.ToString();
            UpdateTimeStamp(dt);
         
            dv.Visible = false;
             
             BindGV(gvPlayer,cid );
        }

        private void sendEmail(string SID, string fname, string lname, string status, string competed, string naia, string hs, string gdate)
        {
            // Find Where the Submission Form e.g Mytest > Default Page > Email Agreement
            string strPortletID = this.ParentPortlet.ID.ToString();
            string strTabPagePortlet = string.Empty;
            string[] strParts = this.ParentPortlet.PortletDisplay.Portlet.ToString().Replace("{CN=" + this.ParentPortlet.PortletDisplay.Portlet.Name + ",", "").Replace(",CN=Portal,O=Jenzabar,C=US}", "").Replace(",OU=Pages", "").Split(',');
            for (int idx = strParts.Length; idx > 0; idx--)
            {
                strTabPagePortlet += strParts[idx - 1].Replace("CN=", "") + " > ";
            }
            strTabPagePortlet += this.ParentPortlet.Title;

            // This is the body of the Email Sent to campusSafety and Student
            // ' Form Submission<br>Where: {0}<br>When: {1}<br>Who: {2}:'  CUS_VEHICLE_REGISTRATION_MSG_RESULTS_BODY_INTRO
            string strResults = "<table border=0> <tr align= left ><th colspan=2>" +
                                    Globalizer.Format("CUS_AURoster_MSG_RESULTS_BODY_INTRO"
                // "<table border=0 cellspacing=0 cellpadding=2><tr align= left ><td align= left colspan='2'><b>SECURITY QUESTION SUBMISSION</b></td></tr> <tr align= left ><td align= left>Where:</td><td align= left >{0}</td></tr> <tr align= left ><td align= left >When:</td><td>{1:D} {1:t}</td></tr> <tr align= left ><td align= left >Who:</td><td>{2}</td></tr><tr align= left ><td align= left colspan='2'><hr/></td></tr></table>" 
                                   ,
                                    strTabPagePortlet,
                                    System.DateTime.Now,
                                    PortalUser.Current.NameDetails.ToString()

                                    )
                                    +
                                    "</th></tr></table>"
                                    ;


            string strSubject = "Athletic Roaster for " + fname + " " + lname + " was modified by Coach " + lblCoach.Text;

            string strToAddress = "Laura.Watson@avila.edu"; //"Mallika.Ramaswamy@avila.edu"; //

            string strBody = String.Empty;
            string strFrom = PortalUser.Current.EmailAddress.ToString();
            string strValue = String.Empty;
            string strCC = "Mallika.Ramaswamy@avila.edu";//"IT@Avila.edu";
            strBody += "<table  >";
            strBody += "<tr ><th  colspan=2   align=left valign=middle> Modified/Updated Student Details </th></tr>";
            //strBody += "<tr ><th    align=left valign=middle >Team: </th><td  align=left valign=middle >" + ddTeam.SelectedValue + "  </td> </tr> ";
            strBody += "<tr ><th    align=left valign=middle > ID# : </th><td  align=left valign=middle >" + SID + "  </td> </tr> ";
            strBody += "<tr ><th    align=left valign=middle >First Name: </th><td  align=left valign=middle >" + fname+ "  </td> </tr> ";
            strBody += "<tr ><th    align=left valign=middle >Last Name: </th><td  align=left valign=middle >" + lname + "  </td> </tr> ";


            strBody += "<tr > <th   align=left  > Status :</th><td   align=left  >" + status + "  </td> </tr> ";
            strBody += "<tr > <th   align=left  > College or HS:  :</th><td   align=left  >" + hs + "  </td> </tr> ";
            
                strBody += "<tr > <th   align=left  > HS GRAD Date:  :</th><td   align=left  >" + gdate + "  </td> </tr> ";
            
            strBody += "<tr > <th   align=left  > Previous Seasons Competed:</th><td   align=left  >" + competed + "  </td> </tr> ";

            strBody += "<tr > <th   align=left  > NAIA EC#:</th><td   align=left  >" + naia + "  </td> </tr> ";

            strBody += " </table> ";
            //// Now send the results, or at least try to
            strResults += strBody;
            // filter out bad From address
            string strNoteReFailedSend = string.Empty;
            string strNoteReBadFromAddressConfig = String.Empty;
            bool blFromAddressWasGood = ((new ValidEmail(strFrom.Trim())).IsValid);
            //not good
            if (!blFromAddressWasGood)
            {
                strNoteReBadFromAddressConfig = Globalizer.GetGlobalizedString("CUS_SIMPLEFORM_MSG_BAD_FROM_ADDR_CONFIG") +
                    " " + strFrom;
                strFrom = ConfigSettings.Current.SmtpDefaultEmailAddress;
            }
            // send the message, but note if it failed
            try
            {
                //sending the email to ITService 
                if (!Email.CreateAndSendMailMessage(strFrom, strToAddress, strCC, strSubject, strResults))
                {
                    //strNoteReFailedSend += "Couldn't send to " + strToAddress + " from " + strFrom + " ";
                    strNoteReFailedSend += "Couldn't send to " + strToAddress + " from " + strFrom + " ";
                }
            }
            catch (Exception ee)
            {
                strNoteReFailedSend += ee.Message + " (see Event Log for details) - Couldn't send to " + strToAddress + " from " + strFrom + " ";

                Jenzabar.Common.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(ee);
            }


            
        }

        private void UpdateTimeStamp(string  dt)
        {
            using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
            {

                try
                {
                    myConn.Open();

                    SqlCommand cmd = new SqlCommand("CUS_sp_AURoster_Coach_Update", myConn);
                    cmd.Parameters.Add("@cid", SqlDbType.VarChar, 10).Value = PortalUser.Current.HostID;
                    cmd.Parameters.Add("@timestamp", SqlDbType.VarChar, 10).Value = dt;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();

                }
                catch (Exception ex)
                {


                    this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error Inserting Data Items: " + ex.Message);
                }
                finally
                {
                    // Close Connection
                    myConn.Close();
                }
            }
        }



      








        public class lsStatus
        {
            public string _sCode;
            public string _sValue;

            public lsStatus(string sCode, string sValue)
            {
                this._sCode = sCode;
                this._sValue = sValue;

            }
            public string StatusCode
            {
                get { return _sCode; }
                set { _sCode = value; }

            }

            public string StatusValue
            {
                get { return _sValue; }
                set { _sValue = value; }

            }

        }


        protected void dv_DataBound(object sender, EventArgs e)
        {
            if (dv.CurrentMode == DetailsViewMode.Edit)
            {
                //Added for dropdown selected value( actually this is already submitted value)
                //For that add the TextBox or Label in the detail view check Edi_view.ascx make it visible false
                TextBox status = (TextBox)dv.FindControl("txtStatus");
                DropDownList dd = (DropDownList)dv.FindControl("ddStatus");
                if (dd != null)
                {
                    List<lsStatus> lstStr = new List<lsStatus>();
                   
                    lstStr.Add(new lsStatus("New FR", "New FR"));
                     lstStr.Add(new lsStatus("New TR", "New TR"));
                     lstStr.Add(new lsStatus("Return", "Return"));
                     lstStr.Add(new lsStatus("Delete", "Delete"));
                  
                    dd.DataSource = lstStr;
                    dd.DataValueField = "StatusCode";
                    dd.DataTextField = "StatusValue";
                    dd.DataBind();
                }

                //dropdown populated already existed data for this add the text control in DV(dv) make it visible false
                dd.SelectedValue = status.Text.Trim();
            }
        }

        protected void dv_ItemCreated(object sender, EventArgs e)
        {
            if (dv.CurrentMode == DetailsViewMode.Edit)
            {
                DropDownList dd = (DropDownList)dv.FindControl("ddStatus");
                if (dd != null)
                {
                    List<lsStatus> lstStr = new List<lsStatus>();

                    lstStr.Add(new lsStatus("New FR", "New FR"));
                    lstStr.Add(new lsStatus("New TR", "New TR"));
                    lstStr.Add(new lsStatus("Return", "Return"));
                    lstStr.Add(new lsStatus("Delete", "Delete"));

                    dd.DataSource = lstStr;
                    dd.DataValueField = "StatusCode";
                    dd.DataTextField = "StatusValue";
                    dd.DataBind();
                }
            }
        }

        //added on 11/5/2014
        protected void gvPlayer_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            dv.Visible = false; 
            // For Paging 
            gvPlayer.Visible = true;
            gvPlayer.PageIndex = e.NewPageIndex;
            cid = PortalUser.Current.HostID;
            lblCoach.Text = PortalUser.Current.FirstName + " " + PortalUser.Current.LastName;
            lblDate.Text = DateTime.Now.ToShortDateString();

            BindGV(gvPlayer, cid);
        }

        

    }
}

//GRIDVIEW EditMode Update is not working for me
//protected void gvPlayer_RowEditing(object sender, GridViewEditEventArgs e)
//{
//    gvPlayer.EditIndex = e.NewEditIndex;
//    BindGV(gvPlayer, cid); // never remove this bind


//}


//protected void gvPlayer_RowUpdating(object sender, GridViewUpdateEventArgs e)
//{

//     // Reset edit mode
//      gvPlayer.EditIndex = -1;
//     BindGV(gvPlayer, cid);
//}

//protected void gvPlayer_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
//{
//    gvPlayer.EditIndex = -1;
//    BindGV(gvPlayer, cid);
//}
//protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
//{
//    gv.EditIndex = e.NewEditIndex;
//    populateEditGV();
//}

//protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
//{
//    int selectedIndex = gvPlayer.SelectedIndex;
//    //Read the ID From the row
//    string SID = (gvPlayer.DataKeys[selectedIndex].Value).ToString();
//    string fname = gv.HeaderRow.Cells[2].ToString();
//    string lname = gv.HeaderRow.Cells[3].ToString();

//    //UpdateRecord(SID, fname, lname);
//}
//private void populateEditGV()
//{
//     using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
//    {

//        try
//        {
//            myConn.Open();
//            //GridViewRow selectedRow = gvPlayer.SelectedRow;
//            int selectedIndex = gvPlayer.SelectedIndex;
//            //Read the ID From the row
//             string id = (gvPlayer.DataKeys[selectedIndex].Value).ToString();

//           // selectedRowSID = selectedRow.Cells[0].Text;
//            SqlCommand cmd = new SqlCommand("SELECT * FROM [TmsEprd].[dbo].[CUS_AURoster_Team] WHERE Student_ID = '" + id +"'" , myConn);
//            SqlDataAdapter da = new SqlDataAdapter(cmd); 

//            DataSet ds = new DataSet();

//            da.Fill(ds, "DataView");

//            //SqlDataReader reader;
//            //reader = cmd.ExecuteReader();
//            gv.DataSource = ds;
//            gv.DataBind();
//        }
//        catch (Exception ex)
//        {
//            this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error retrieving Data. test " + ex.Message);
//            // this.ParentPortlet.NextScreen("Default");

//        }
//        finally
//        {

//            myConn.Close();
//        }

//    }
//}

//string selectedRowSID;